#!/usr/bin/env python

import sys
import commands
import os
import signal

def restart(req, chatName=None, action=None):
    if chatName == None:
        chatName = sys.argv[1]
	
    if chatName == None:
        print "Usage: starter.py chat_name start|stop"
	return
    
    if action == None:
        action = sys.argv[2]
	
    if (action == None or (action != "start" and action != "stop")):
        action = "start"

    if req != None:
        from mod_python import apache
        req.content_type = "text/html"

    os.umask(0)	
    botsDir = "/home/msshu/gtalk_bots/"
    pidFilePath = botsDir + chatName + "/process.pid"
    startLogPath = botsDir + chatName + "/start.log"
    if os.path.exists(pidFilePath):
        pidFile = open(pidFilePath, 'rw')
        pidNumberString = pidFile.read()
        pidFile.close()
    
        if (pidNumberString != None and len(pidNumberString) > 0):
            pidNumber = int(pidNumberString)

            cnt = 10
            while cnt > 0:
                try:
	            os.kill(pidNumber, signal.SIGKILL)
		    killedpid, stat = os.waitpid(pidNumber, os.WNOHANG)
		    if killedpid == 0:
		        f = open(startLogPath, 'w')
		        f.write("can not kill process by pid ")
		        f.write(pidNumberString)
		        f.write('\n')
		        f.write("try #")
		        f.write(str(10 - cnt + 1))
		        f.write('\n')
		        f.close()
		    else:
		        os.remove(pidFilePath)

		except OSError, value:
		    f = open(startLogPath, 'w')
		    f.write("can not kill process by pid ")
		    f.write(pidNumberString)
		    f.write('\n')
		    f.close()
		    os.remove(pidFilePath)
		    break
		
		cnt = cnt - 1
	else:
	    os.remove(pidFilePath)
	    	    
    if action == "start":
        pid = os.fork()
	if pid:
	    pidFile = open(pidFilePath, 'w')
	    pidFile.write(str(pid))
	    pidFile.close()
        else:
	    botHomeDir = botsDir + chatName
	    os.chdir(botHomeDir)
	    
	    STDOUT = 1
            while STDOUT < 3:
                logPath = botsDir + chatName 
                if STDOUT == 1:
                    logPath = logPath + ".log"
                else:
                    logPath = logPath + ".error.log"
                logFile = None
                if os.path.exists(logPath):
                    logFile = os.open(logPath, os.O_WRONLY | os.O_APPEND)
                else:
                    logFile = os.open(logPath, os.O_CREAT | os.O_WRONLY)
                os.dup2(logFile, STDOUT)
                os.close(logFile)
                STDOUT = STDOUT + 1
	    
            sys.path.append(botHomeDir)
	    import cbot2
	    cbot2.startBot()
	    return

    if req != None:
        req.write("<html> <META HTTP-EQUIV=\"Refresh\" CONTENT=\"5; URL=https://botva.bwtele.com\"> </html>")
	    
def startRussianChat(req):
    restart(req, "govorim.po.russki", "start")
    
def stopRussianChat(req):
    restart(req, "govorim.po.russki", "stop")
    
def startEnglishChat(req):
    restart(req, "we.speak.english", "start")
    
def stopEnglishChat(req):
    restart(req, "we.speak.english", "stop")

def startCzechChat(req):
    restart(req, "mluvime.cesky", "start")
    
def stopCzechChat(req):
    restart(req, "mluvime.cesky", "stop")
    
def startSpanishChat(req):
    restart(req, "nosotros.hablamos.espanol", "start")
    
def stopSpanishChat(req):
    restart(req, "nosotros.hablamos.espanol", "stop")
    
def startUkrainianChat(req):
    restart(req, "hovorymo.ukrajinskoju", "start")
    
def stopUkrainianChat(req):
    restart(req, "hovorymo.ukrajinskoju", "stop")

def onPostCommit(req):
    from mod_python import apache
    s = commands.getoutput("exec /home/msshu/gtalk_bots/update_bots")
    startCzechChat(None)
    startEnglishChat(None)
    startUkrainianChat(None)
    startRussianChat(None)
    startSpanishChat(None)
    req.write("%s" % s)
    return apache.OK

if __name__ == "__main__":
    restart(None)
